package com.example.demo.util.ssl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Iterator;

public class SimpleX509TrustManager implements X509TrustManager {

    private Logger logger = LoggerFactory.getLogger(SimpleKeyStoreTrustManager.class);

    private X509TrustManager actualTrustManager;

    public SimpleX509TrustManager(InputStream inputCert) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(null, null);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> cs = cf.generateCertificates(inputCert);
        X509Certificate[] rslt = new X509Certificate[cs.size()];
        int i = 0;
        for (Iterator itor = cs.iterator(); itor.hasNext(); i++) {
            ks.setCertificateEntry("cert" + i, (Certificate) itor.next());
        }
        String algorithm = TrustManagerFactory.getDefaultAlgorithm();
        logger.debug("build trustmanagerfactory use :" + algorithm);
        TrustManagerFactory factory = TrustManagerFactory
                .getInstance(algorithm);
        factory.init(ks);
        TrustManager[] trustManagers = factory.getTrustManagers();
        if (trustManagers.length <= 0) {
            throw new NoSuchAlgorithmException("trustManager not found!");
        }
        actualTrustManager = (X509TrustManager) trustManagers[0];
    }

    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        actualTrustManager.checkClientTrusted(arg0, arg1);
    }

    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        actualTrustManager.checkServerTrusted(arg0, arg1);
    }

    public X509Certificate[] getAcceptedIssuers() {
        return actualTrustManager.getAcceptedIssuers();
    }


}
